<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Pro;
use Auth;
use App\Bid;
use DB;

class TouController extends Controller
{
    protected $middleware = ['App\Http\Middleware\Authenticate' => []];
    public function touzi($pid)
    {
        //print_r($pid);exit;
        $pros = Pro::find($pid);
        return view('lijitouzi', ['pro' => $pros]);
    }
    public function touziPost(Request $req, $pid)
    {
        //print_r($_POST);exit;
        $pros = Pro::find($pid);
        $bid = new Bid();
        $users = Auth::User();
        //print_r($users);exit;
        $bid->uid = $users->uid;
        $bid->pid = $pros->pid;
        $bid->title = $pros->title;
        $bid->money = $req->money * 100;
        if($req->money * 100 > ($pros->money - $pros->recive)){//如果$req填的money大于$bid的钱减去已投资的钱
            return redirect("/touzi/$pid");
        }
        $bid->pubtime = time();
        //dd($bid);exit;
        $bid->save();

        $pros->recive += $bid->money;
        $pros->save();
        /*修改项目里的金额添加进去*/
        if ($pros->money == $pros->recive) {
            //$pros->status = 2;
            $this->touziDone($pros);
        }
        
    }
    /*还款与收益表*/
    protected function touziDone($pros)
    {
        /*修改招标项目的状态为2(还款中)*/
        $pros = Pro::find($pros->pid);
        $pros->status = 2;
        //$pros->save();
        
        //为借款人,n个月还款周期,生成n条还款记录
        $amount = ($pros->money * $pros->rate / 100 / 12) + ($pros->money / $pros->hrange);
        //$amount = ($pros->money * $pros->rate / 1200)

        $row = ['uid'=>$pros->uid , 'pid'=>$pros->pid ,'title'=>$pros->title];
        $row['amount'] = $amount;
        $row['status'] = 0;
        //print_r($row);exit;
        $today = date('Y-m-d');
        for($i=1;$i<=$pros->hrange;$i+=1){
            $row['paydate'] = date('Y-m-d' , strtotime("+ {$i}months"));
                DB::table('hks')->insert($row);
        }
        //为收益者,生成收益记录
        $bids = Bid::where('pid' , $pros->pid)->get();
        
        $row=[];
        $row['pid'] = $pros->pid;
        $row['title'] = $pros->title;
        $row['enddate'] = date('Y-m-d' , strtotime("+ {$pros->hrange}months"));

        foreach($bids as $bid){
            $row['uid'] = $bid->uid;
            $row['amount'] = $bid->money * $pros->rate / 36500;
            //print_r($row);exit;
            //投的钱乘以利率然后除以一年是365天然后是按百分比所以再除以100就是36500
            DB::table('tasks')->insert($row);
        }
}
}